
function getQueryVariable(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable)
		{
			return pair[1];
		}
	}
} 

function createXMLHttpRequest()
{
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   alert("XMLHttpRequest not supported");
   return null;
}

function DoHttp(url)
{
	this.xhReq = createXMLHttpRequest();
	this.xhReq.open("GET", url, false); // Server stuck in a loop./* the false here makes it synchronous */
	this.xhReq.send(null);
	if (this.xhReq.status == 200)
	{ /* the request has been returned */
//		alert("request successful")
	}
	else
	{
		alert('error in get to ' + url + ' this.xhReq.status' + this.xhReq.status);
	}
	// var requestTimer = setTimeout(function()
		// {
		   // this.xhReq.abort();
		   // // Handle timeout situation, e.g. Retry or inform user.
		// }, 4000); //MAXIMUM_WAITING_TIME); 
	// this.xhReq.onreadystatechange = function()
	// {
	 // alert('start2');
		 // if (this.xhReq.readyState != 4)  { return; }
		 // clearTimeout(requestTimer); 
		 // if (this.xhReq.status != 200)  {
		   // // Handle error, e.g. Display error message on page
		   // return;
	 // }
//	};		

	return this.xhReq.responseText;
}

function randomDate(startDate, endDate)
{
	var startMillis = startDate.getTime(); //Get millis for January 1st 1900
	var endMillis = endDate.getTime(); //Get millis for January 1st 2100
	var randomDate = new Date(startMillis + Math.random()*(endMillis-startMillis)); //new Date() with millis set to random value between startMillis and endMillis
	randomDate.toUTCString(); //Output UTC string for randomDate
}

function StringTrim(startString)
{
	var result = startString.replace(/^\s+|\s+$/g, '') ;
	return result;
}

function getTemp(containingString) //  temperature logger specific todo maybe json
{	// pin 0 : -272.86
	if(containingString.indexOf(":") >= 0 )
	{
		var split = containingString.split(":");
		var result = StringTrim(split[1]);
		return result;
	}
	else
	{
		return "";
	}
}

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]); // months are 0-based
}


function LoadTemperatureFile(wholeFile)
{
//2011-09-25 09:30:15 :: pin 0 : -272.86; pin 1 : -218.95; pin 2 : -220.11; pin 3 : 61.91; pin 4 : 10.37; pin 5 : 10.06; 
//alert('start LoadTemperatureFile');

	var d = new Date()
	var gmtHours = -d.getTimezoneOffset()/60;

	if(wholeFile.indexOf("::") >= 0 )
	{
//		var lines = wholeFile.split("\\r?\\n");
		var series0Data = new Array();
		var series1Data = new Array();
		var series2Data = new Array();

		var lines = wholeFile.split("\n");
		for(i=0; i<lines.length; i++)
		{
			var returnArrays = LoadLine(lines[i], gmtHours);

			if(returnArrays != null)
			{
				if(returnArrays[0] != null)
					series0Data.push(returnArrays[0]);
				if(returnArrays[1] != null)
					series1Data.push(returnArrays[1]);
				if(returnArrays[2] != null)
					series2Data.push(returnArrays[2]);
			}
		}
//alert('series0' + series0);
		return [series0Data, series1Data, series2Data];
	}
	else
	{
		return false;
		alert('LoadTemperatureFile false');
	}
}

function LoadLine(currentLine, timeDifference)
{
//2011-09-25 09:30:15 :: pin 0 : -272.86; pin 1 : -218.95; pin 2 : -220.11; pin 3 : 61.91; pin 4 : 10.37; pin 5 : 10.06; 
	if(currentLine.indexOf("::") >= 0 && currentLine.length > 113)// all good lines seems to have this length todo fix in logger
	{
		var datePart = currentLine.split("::")[0];
		var dateMillisGMT = parseDate(datePart).getTime();
		var dateMillis = dateMillisGMT + timeDifference*60*60*1000;// bring millis to local time
		var tempParts = currentLine.split("::")[1];
		var tempSplit = tempParts.split(";");
		var newSeries0Temp = getTemp(tempSplit[3]);
		var newSeries1Temp = getTemp(tempSplit[4]);
		var newSeries2Temp = getTemp(tempSplit[5]);
		var line0Temp = tempSanityCheck(parseFloat(newSeries0Temp));
		var line1Temp = tempSanityCheck(parseFloat(newSeries1Temp));
		var line2Temp = tempSanityCheck(parseFloat(newSeries2Temp));

		var line0Data = [dateMillis, line0Temp];
		var line1Data = [dateMillis, line1Temp];
		var line2Data = [dateMillis, line2Temp];
		return [line0Data, line1Data, line2Data];
	}
	else
	{
		//alert('failed line');
		return null;
	}
}

function tempSanityCheck(temp)
{
	if(temp > 108 || temp < -5)
	{
		return null;
	}
	else
	{
		return temp;
	}
}

function clone(obj)
{
	// Handle the 3 simple types, and null or undefined
	if (null == obj || "object" != typeof obj) return obj;

	// Handle Date
	if (obj instanceof Date) {
		var copy = new Date();
		copy.setTime(obj.getTime());
		return copy;
	}

	// Handle Array
	if (obj instanceof Array) {
		var copy = [];
		for (var i = 0; i < obj.length; ++i) {
			copy[i] = clone(obj[i]);
		}
		return copy;
	}

	// Handle Object
	if (obj instanceof Object) {
		var copy = {};
		for (var attr in obj) {
			if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
		}
		return copy;
	}

	throw new Error("Unable to copy obj! Its type isn't supported.");
}
